import { ShoppingService } from "services/shopping";
import React = require("react");
import { FormValidator, rules as r } from "maishu-dilu";
import * as wuzhui from "maishu-wuzhui";
import { createGridView } from "maishu-wuzhui-helper";
import ReactDOM = require("react-dom");
import * as ui from "maishu-ui-toolkit";
import { Service } from "services/service";
import { ItemDialog, ItemDialogState } from "controls/item-dialog";

let shopping = Service.createInstance(ShoppingService);
export default class SolutionListPage extends React.Component<any, any>{
    private gridViewElement: HTMLTableElement;
    dataSource: wuzhui.DataSource<FreightSolution>;
    items = new Array<FreightSolution>();
    private solutionDialog: SolutionDialog;

    constructor(props) {
        super(props);
    }
    componentDidMount() {
        let dataSource = this.dataSource = new wuzhui.DataSource<FreightSolution>({
            select: async () => {
                let r = await shopping.freightSolutions();
                return { dataItems: r, totalRowCount: r.length };
            },
            delete: (dataItem) => shopping.deleteFreightSolution(dataItem),
            update: (dataItem) => shopping.updateFreightSolution(dataItem),
            insert: (dataItem) => shopping.addFreightSolution(dataItem),
            primaryKeys: ['Id']
        });

        dataSource.selected.add((sender, result) => {
            this.items = result.dataItems;
        })

        let it = this;
        let gridView = createGridView({
            element: this.gridViewElement,
            columns: [
                new wuzhui.BoundField({
                    dataField: 'Id', headerText: '编号',
                    headerStyle: { width: '300px' } as CSSStyleDeclaration
                }),
                new wuzhui.BoundField({
                    dataField: 'Name', headerText: '名称',
                }),
                new wuzhui.CustomField<FreightSolution>({
                    createItemCell(dataItem) {
                        let cell = new IsDefaultCell(it, dataItem)
                        return cell;
                    },
                    itemStyle: { textAlign: 'center', width: '100px' } as CSSStyleDeclaration,
                    headerText: '是否默认'
                }),
                new wuzhui.CustomField<FreightSolution>({
                    createItemCell(dataItem) {
                        let cell = new wuzhui.GridViewCell();
                        ReactDOM.render(
                            <div>
                                <button className="btn btn-info btn-minier" style={{ marginRight: 4 }}
                                    onClick={() => it.showDialog(dataItem)}>
                                    <i className="icon-pencil"></i>
                                </button>
                                <button className="btn btn-minier btn-danger" style={{ marginRight: 4 }}
                                    ref={(e: HTMLElement) => {
                                        if (!e) return;
                                        e.onclick = ui.buttonOnClick(() => dataSource.delete(dataItem),
                                            { confirm: `确定要删除'${dataItem.Name}'运费方案吗` });
                                    }}>
                                    <i className="icon-trash"></i>
                                </button>
                                <a className="btn btn-info btn-minier" style={{ marginRight: 4 }}
                                    href={`#freight/freight-list?id=${dataItem.Id}&name=${encodeURI(dataItem.Name)}`}>设置运费</a>
                            </div>, cell.element);
                        return cell;
                    },
                    headerText: '操作',
                    headerStyle: { width: '180px' } as CSSStyleDeclaration,
                    itemStyle: { textAlign: 'center' } as CSSStyleDeclaration,
                })
            ],
            dataSource,
            pageSize: null
        });
    }
    showDialog(dataItem?: FreightSolution) {
        dataItem = dataItem || {} as FreightSolution;
        let title = dataItem ? '编辑运费模板' : '添加运费模板';
        this.solutionDialog.show(dataItem, title, (item) => {
            if (!item.Id)
                this.dataSource.insert(item);
            else
                this.dataSource.update(item);
        })
    }
    render() {
        return <>
            <div className="tabbable">
                <ul className="nav nav-tabs">
                    <li className="pull-right">
                        <button data-bind="click:newItem" className="btn btn-primary btn-sm"
                            onClick={() => this.showDialog()}>
                            <i className="icon-plus"></i>
                            <span>新建运费模板</span>
                        </button>
                    </li>
                </ul>
            </div>
            <table ref={(e: HTMLTableElement) => this.gridViewElement = e || this.gridViewElement}>
            </table>
            <SolutionDialog ref={e => this.solutionDialog = e || this.solutionDialog} />
        </>
    }
}


class IsDefaultCell extends wuzhui.GridViewDataCell<FreightSolution> {
    dataItem: FreightSolution;
    solutionListPage: SolutionListPage;
    constructor(solutionListPage: SolutionListPage, dataItem: FreightSolution) {
        super({ render: null })
        this.dataField = 'IsDefault';
        this.solutionListPage = solutionListPage;
        this.dataItem = dataItem;
    }
    render(value) {
        ReactDOM.render(value != true ?
            <button className="btn btn-minier btn-primary"
                ref={(e: HTMLButtonElement) => {
                    if (!e) return;
                    ui.buttonOnClick(e, async () => {
                        let shopping = Service.createInstance(ShoppingService);

                        let dataItem = this.dataItem;
                        let it = this.solutionListPage;
                        let result = await shopping.setDefaultFreightSolution(dataItem.Id);
                        dataItem.IsDefault = true;
                        it.items.forEach(item => {
                            item.IsDefault = item == dataItem;
                            it.dataSource.updated.fire(it.dataSource, item);
                        })
                        return result;
                    })
                }}>设为默认 </button> :
            <span>默认方案</span>,
            this.element
        );
    }
}

class SolutionDialog extends ItemDialog<{}, FreightSolution, ItemDialogState<FreightSolution>> {
    private NAME = "Name";
    componentDidMount() {
        this.validator = new FormValidator(this.element,
            { name: this.NAME, rules: [r.required("请输入运费模板的名称")] }
        );
    }
    render() {
        let { item: dataItem } = this.state;
        return <>
            <div className="form-group clearfix">
                <label className="col-sm-2 control-label">名称*</label>
                <div className="col-sm-10">
                    <input name={this.NAME} type="text" className="form-control"
                        placeholder="请输入运费模板的名称"
                        value={dataItem.Name || ""}
                        onChange={(e) => {
                            dataItem.Name = (e.target as HTMLInputElement).value;
                            this.setState({ item: dataItem });
                        }}
                    />
                </div>
            </div>
            <div className="form-group clearfix">
                <label className="col-sm-2 control-label">默认运费</label>
                <div className="col-sm-10">
                    <input name="freight" type="text" className="form-control" placeholder="在该模板下，适用于大部分地区的运费"
                        onChange={(e) => {
                            if (!r.numeric().validate(e.target.value))
                                return;

                            dataItem.DefaultFreight = Number.parseFloat((e.target as HTMLInputElement).value)
                        }} />
                </div>
            </div>
        </>
    }
}

